import axios from 'axios';
import BSPError from './bsperror';
let logger = require('./../commons/logger');

class HttpRequest {
  get(ctx, url, params) {
    return this.ajax('get', url, ctx, params);
  }

  post(ctx, url, params) {
    return this.ajax('post', url, ctx, params);
  }

  del(ctx, url, params) {
    return this.ajax('delete', url, ctx, params);
  }

  put(ctx, url, params) {
    return this.ajax('put', url, ctx, params);
  }

  ajax(method, url, ctx, params) {
    let account = ctx && ctx.session && ctx.session.personId || '';
    let userName = ctx && ctx.session && ctx.session.name || '';
    const user = { userId: 'wechat-shengjing360', personId: account, userName: userName };
    logger.info('ajax',{
      method,
      url,
      params,
      account
    });
    let ajaxRequest = null;
    if (method === 'get' || method === 'delete') {
      ajaxRequest = axios({
        method: method,
        url: url,
        headers: {
          user: JSON.stringify(user)
        },
        ...params
      })
    } else {
      ajaxRequest = axios({
        method: method,
        url: url,
        data: params,
        headers: {
          user: JSON.stringify(user)
        }
      })
    }
    return ajaxRequest
      .then((res) => {
        if (res.data && res.data.code === 10000) {
          return Promise.resolve(res.data);
        } else {
          throw new BSPError(res.data);
        }
      }).catch((err) => {
        if ( err instanceof BSPError) {
          return Promise.reject(err);
        } else if (!err.response) { // 网络失败
          return Promise.reject(new BSPError({code: '00000', msg: '发生了网络错误'}));
        } else {
          if (err.response.status === 404) {
            return Promise.reject(new BSPError({code: '00000', msg: '请求的资源不存在'}));
          } else {
            let data = err.response.data;
            return Promise.reject(new BSPError(data));
          }
        }
      });
  }
}

export default new HttpRequest();
